package com.nervenets.web.controller.handler.user.user;

import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.controller.handler.user.UserModel;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;

public class UserMobileChangeHandler extends Handler<UserMobileChangeParams> {
    @Override
    public String handle(UserMobileChangeParams params, HttpServletRequest request) throws Exception {
        if (!params.getVCode().equals(globalService.getGlobalPair(String.format(Global.Constants.MOBILE_VALIDATION_CODE, params.getMobile())))) {
            return errorMessage(MessageCode.code_444, "您填写的验证码不正确或失效！");
        }
        return (String) redisSyncLocker.idLock(params.getUserId(), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                final User user = userDao.findById(params.getUserId(), User.class);
                user.setMobile(params.getMobile());
                user.setPassword(params.getPassword());
                userDao.saveOrUpdate(user);
                globalService.clearRedisUserStored(params.getUserId());
                return successMessage(new UserModel(user, 1, globalVariablesService.getGlobalRule().getDefaultAvatar()));
            }
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
